package cn.bone.web.base;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by superbone on 2017/4/18.
 */
@Controller
public class BaseController {

    Logger logger = LoggerFactory.getLogger("登录测试");

    @RequestMapping("/test")
    @ResponseBody
    public String test(){

        return "test";
    }

    @RequestMapping("/login")
    public String login(){
        return "/login";
    }

    @RequestMapping("/main")
    public String main(){
        return "/main";
    }

    @RequestMapping("/memberLogin")
    public String memberLogin(String username, String password, HttpServletRequest request){
        System.out.println("HomeController.login");

        UsernamePasswordToken token = new UsernamePasswordToken(username, password,request.getRemoteAddr());
        String msg = null;
        try {
            SecurityUtils.getSubject().login(token);
        } catch (AuthenticationException e) {
            logger.debug("Error authenticating.", e);
            if (e instanceof UnknownAccountException) {
                msg = "未知账户！";
            } else if (e instanceof LockedAccountException) {
                msg = "账户已锁定！";
            } else if (e instanceof IncorrectCredentialsException) {
                msg = "密码不正确！";
            } else if (e instanceof ExcessiveAttemptsException) {
                msg = "用户名或密码错误超过5次,请5分钟后重试";
            } else if (e instanceof ConcurrentAccessException) {
                msg = "用户已登录！";
            } else if (e instanceof org.apache.shiro.authc.AccountException) {
                msg = "未知帐号错误或用户状态异常！";
            } else if (e instanceof AuthenticationException) {
                msg = "认证失败！";
            }
            if (StringUtils.isEmpty(msg)) {
                msg = "用户名密码错误！";
            }
        }
        if(!StringUtils.isEmpty(msg)){
            request.setAttribute("errorMsg",msg);
        }
        System.out.println("msg:"+msg);
        return "/login";
    }
}
